package ru.ifmo.cppsc;

import ru.ifmo.cppsc.grammar.AttributedSymbol;
import ru.ifmo.cppsc.grammar.Grammar;
import ru.ifmo.cppsc.grammar.ProperGrammar;
import ru.ifmo.cppsc.workers.FileWorker;
import ru.ifmo.cppsc.syntactic.TreeNode;
import ru.ifmo.cppsc.syntactic.WeakPrecedenceAnalyse;
import ru.ifmo.cppsc.syntactic.LRParser;
import ru.ifmo.cppsc.translator.TranslatorCodeGenerator;
import ru.ifmo.cppsc.translator.Translator;
import ru.ifmo.cppsc.translator.SymbolTable;
import ru.ifmo.cppsc.translator.generated.CodeContainer;
import ru.ifmo.cppsc.lexer.Lexer;
import ru.ifmo.cppsc.lexer.token.Token;
import ru.ifmo.cppsc.auxilary.FileHelper;

import java.util.ArrayList;

/**
 * Author: Olga Komaleva
 * Date: Jun 17, 2008
 */

public class Main {
    public static void main(String[] args) {
        boolean convertMode = false;

        if ( convertMode ) {
            ProperGrammar grammar = new ProperGrammar("./data/grammar/grammar4.y");
            //grammar.saveAsXML("./data/grammar.xml");
            WeakPrecedenceAnalyse wpa = new WeakPrecedenceAnalyse(grammar);
            wpa.saveTable("table.dat");
            wpa.printRelations();
            //FileWorker.saveGrammar("./data/grammar_short2_.y", grammar);
        }
        else {
            ProperGrammar grammar = new ProperGrammar("./data/grammar.xml");

            //TranslatorCodeGenerator codeGenerator = new TranslatorCodeGenerator();
            //codeGenerator.generateCode(grammar);

            WeakPrecedenceAnalyse wpa = new WeakPrecedenceAnalyse(grammar);
            Lexer lexer = new Lexer ();

            ArrayList<Token> tokenList = new ArrayList<Token> ();
            tokenList = lexer.parse ( FileHelper.getFileContents("input.cpp"));

            SymbolTable symbolTable = new SymbolTable();
            CodeContainer.table = symbolTable;
            CodeContainer.generateMap();
            ArrayList<AttributedSymbol> symList = new ArrayList<AttributedSymbol> ();
            symList.add(new AttributedSymbol(wpa.STOP_SYMBOL));
            for ( Token token : tokenList ) {
                symList.add(new AttributedSymbol(grammar, token, symbolTable));
            }
            symList.add(new AttributedSymbol(wpa.STOP_SYMBOL));

            LRParser lrParser = new LRParser(wpa);
            TreeNode root = lrParser.parse(symList);
            if ( root == null ) {
                System.out.println("Syntax error in program.");
            } else {
                Translator translator = new Translator();
                translator.translate(root);
            }
        }
    }
}
